import React, { useState, useRef } from 'react';
import { EditableProTable } from '@ant-design/pro-table';
import { Button, message } from 'antd';
import FormItem from 'antd/lib/form/FormItem';
import { handleReturnArray } from '@/utils/utils';
import { queryRule, updateRule, addRule, removeRule, configureRule } from './service';

const EditTable = (props) => {
  const [editableKeys, setEditableRowKeys] = useState([]);
  const [dataSource, setDataSource] = useState([]);
  const [position, setPosition] = useState('top');
  const [count, setCount] = useState({});
  const actionRef = useRef();
  const [newRecord, setNewRecord] = useState({
    id: (Math.random() * 1000000).toFixed(0),
    decs: '随便',
  });

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      // 第二行不允许编辑
      editable: (text, record, index) => {
        return index !== 1;
      },
      width: '25%',
    },
    {
      title: 'key',
      dataIndex: 'configKey',
      width: '20%',
    },
    {
      title: 'value',
      dataIndex: 'configValue',
      width: '20%',
    },
    {
      title: '状态',
      dataIndex: 'dataType',
      valueType: 'select',
      width: '15%',
      valueEnum: {
        string: { text: '字符串', status: 'Default' },
        int: {
          text: '数字',
          status: 'Processing',
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            var _a;
            (_a = action.startEditable) === null || _a === void 0
              ? void 0
              : _a.call(action, record.id);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  const add = () => {
    return {
      id: (Math.random() * 1000000).toFixed(0),
      dataType: 'string',
      isAdd: true,
    };
  };

  const addArr = async (record) => {
    if (record.isAdd === true) {
      const hide = message.loading('正在添加');
      record.deviceId = props.deviceInfo.id;
      record.configType = 0;
      record.type = 1;
      try {
        await addRule({ ...record });
        hide();
        message.success('添加成功');
        actionRef.current.reload();
        return true;
      } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
      }
    } else {
      const hide = message.loading('正在修改');
      try {
        const response = await updateRule({
          configKey: record.configKey,
          configValue: record.configValue,
          type: record.type,
          id: record.id,
          dataType: record.dataType,
          version: record.version + 1,
          deviceId: props.deviceInfo.id,
          configType: 0,
        });
        if (response.code === 999) {
          throw new Error();
        }
        hide();
        message.success('修改成功');
        actionRef.current.reload();
        return true;
      } catch (error) {
        hide();
        message.error('修改失败请重试！');
        return false;
      }
    }
  };
  const deleteArr = async (record) => {
    const hide = message.loading('正在删除');
    const newData = [...dataSource];
    const index = newData.findIndex((item) => record.id === item.id);
    try {
      await removeRule(record.id);
      hide();
      newData.splice(index, 1);
      setDataSource(newData);
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const configDevice = async () => {
    const hide = message.loading('正在同步');
    try {
      await configureRule(props.deviceInfo.id);
      hide();
      message.success('同步成功，请重试');
      return true;
    } catch (error) {
      hide();
      message.error('同步失败，请重试');
      return false;
    }
  };

  return (
    <EditableProTable
      rowKey="id"
      headerTitle="配置列表"
      recordCreatorProps={{
        position,
        record: add(),
      }}
      bordered
      actionRef={actionRef}
      columns={columns}
      request={(params, sorter, filter) => {
        params.sn = props.deviceInfo.sn;
        return queryRule({ ...params, sorter, filter });
      }}
      postData={(payload) => {
        const { list, total } = payload;
        setCount(total);
        setDataSource(list);
        return list;
      }}
      toolBarRender={() => {
        return [
          <Button
            type="primary"
            key="save"
            onClick={() => {
              // dataSource 就是当前数据，可以调用 api 将其保存
              configDevice();
            }}
          >
            同步
          </Button>,
        ];
      }}
      pagination={{
        showSizeChanger: false,
        showQuickJumper: true,
        position: ['bottomCenter'],
        size: 'small',
        defaultPageSize: 30,
        total: count,
        showTotal: (total) => `共${total}条`,
      }}
      value={dataSource}
      editable={{
        editableKeys,
        onSave: (k, r) => {
          addArr(r);
        },
        onDelete: (k, r) => {
          deleteArr(r);
        },
        onChange: setEditableRowKeys,
      }}
    />
  );
};

export default EditTable;
